package com.dws.xchat.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.dws.xchat.bean.User;
import com.dws.xchat.dao.UserDao;
import com.dws.xchat.exception.UserException;
import com.dws.xchat.util.ExceptionConstant;

@Controller
@RequestMapping("login")
public class LoginController {

	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private UserDao userDao;

	@RequestMapping(method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, @RequestParam("password") String password,
			HttpSession session, Map<String, Object> model) {

		try {
			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
				model.put("error_message", ExceptionConstant.USERNAME_PASSWORD_EMPTY);
				throw new UserException(ExceptionConstant.USERNAME_PASSWORD_EMPTY);
			}

			User user = userDao.findUser(username);
			if (user == null) {
				model.put("error_message", ExceptionConstant.USERNAME_NOT_EXIST);
				throw new UserException(ExceptionConstant.USERNAME_NOT_EXIST);
			}
			if (!user.getPassword().equals(password)) {
				model.put("error_message", ExceptionConstant.PASSWORD_ERROR);
				throw new UserException(ExceptionConstant.PASSWORD_ERROR);
			}
			
			session.setAttribute("password", password);
			session.setAttribute("user_id", user.getId());
			model.put("username", user.getUsername());
			return "main";
		} catch (RuntimeException ex) {
			log.error(ex.getLocalizedMessage());
			return "index";
		}
	}

}
